<template>
  <div class="min-h-screen bg-gray-100 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-md">
      <div>
        <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">登录账号</h2>
        <p class="mt-2 text-center text-sm text-gray-600">
          还没有账号？
          <router-link to="/register" class="text-primary hover:text-primary-dark">
            立即注册
          </router-link>
        </p>
      </div>

      <!-- 账号密码登录 -->
      <div v-if="loginType === 'password'">
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            class="mt-8 space-y-6"
        >
          <el-form-item prop="phone">
            <el-input
                v-model="form.phone"
                placeholder="手机号"
                :prefix-icon="User"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
                v-model="form.password"
                type="password"
                placeholder="密码"
                :prefix-icon="Lock"
                show-password
            />
          </el-form-item>

          <div>
            <el-button
                type="primary"
                class="w-full"
                :loading="loading"
                @click="handleLogin"
            >
              登录
            </el-button>
          </div>
        </el-form>
      </div>

      <!-- 验证码登录 -->
      <div v-else-if="loginType === 'code'" class="mt-8">
        <el-form :model="codeForm" :rules="codeRules" ref="codeFormRef">
          <el-form-item prop="phone">
            <el-input
                v-model="codeForm.phone"
                placeholder="请输入手机号"
                :prefix-icon="Iphone"
            />
          </el-form-item>

          <el-form-item prop="code" class="verify-code-item">
            <div class="flex gap-2">
              <el-input
                  v-model="codeForm.code"
                  placeholder="请输入验证码"
                  :prefix-icon="Message"
              />
              <el-button
                  type="primary"
                  :disabled="countdown > 0"
                  class="w-32 !flex-shrink-0"
                  @click="handleSendCode"
              >
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>

          <el-button
              type="primary"
              class="w-full"
              :loading="loading"
              @click="handleCodeLogin"
          >
            登录
          </el-button>
        </el-form>
      </div>

      <!-- 扫码登录 -->
      <div v-else class="mt-8 flex flex-col items-center space-y-4">
        <QrCode></QrCode>
      </div>

      <!-- 其他登录方式 -->
      <div class="mt-6">
        <div class="relative">
          <div class="absolute inset-0 flex items-center">
            <div class="w-full border-t border-gray-300"></div>
          </div>
          <div class="relative flex justify-center text-sm">
            <span class="px-2 bg-white text-gray-500">其他登录方式</span>
          </div>
        </div>

        <div class="mt-6 flex justify-center space-x-4">
          <el-button
              :class="{'text-primary': loginType === 'password'}"
              @click="loginType = 'password'"
          >
            <el-icon>
              <User/>
            </el-icon>
            <span class="ml-1">密码登录</span>
          </el-button>

<!--          <el-button-->
<!--              :class="{'text-primary': loginType === 'code'}"-->
<!--              @click="loginType = 'code'"-->
<!--          >-->
<!--            <el-icon>-->
<!--              <Message/>-->
<!--            </el-icon>-->
<!--            <span class="ml-1">验证码登录</span>-->
<!--          </el-button>-->

          <el-button
              :class="{'text-primary': loginType === 'qr'}"
              class="max-sm:hidden"
              @click="loginType = 'qr'"
          >
            <el-icon>
              <Iphone/>
            </el-icon>
            <span class="ml-1">扫码登录</span>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onUnmounted, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {useUserStore} from '@/stores/user'
import {ElMessage} from 'element-plus'
import {User, Lock, Message, Iphone} from '@element-plus/icons-vue'
import QrCode from "@/components/auth/QrCode.vue";

const router = useRouter()
const userStore = useUserStore()
const formRef = ref(null)
const loading = ref(false)

onMounted(() => {
  if (userStore.token) {
    router.replace("/")
  }
})
// 登录方式
const loginType = ref('password')

// 账号密码登录表单
const form = ref({
  phone: '',
  password: '',
})

const rules = {
  phone: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
  ]
}

// 验证码登录相关
const codeFormRef = ref(null)
const codeForm = ref({
  phone: '',
  code: ''
})

const codeRules = {
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {len: 6, message: '验证码长度为6位', trigger: 'blur'}
  ]
}

// 倒计时
const countdown = ref(0)
let timer = null

// 发送验证码
const handleSendCode = async () => {
  try {
    await codeFormRef.value.validateField('phone')
    await userStore.sendCode(codeForm.value.phone)
    ElMessage.success('验证码已发送')
    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
  }
}

// 账号密码登录
const handleLogin = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      try {
        await userStore.loginWithPassword(form.value)
        ElMessage.success('登录成功')
        await router.push('/')
      } catch (error) {
        ElMessage.error(error.message || '登录失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 验证码登录
const handleCodeLogin = async () => {
  if (!codeFormRef.value) return

  try {
    await codeFormRef.value.validate()
    loading.value = true

    await userStore.loginWithCode(codeForm.value.phone, codeForm.value.code)
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    loading.value = false
  }
}

// 组件销毁时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.verify-code-item :deep(.el-form-item__content) {
  display: block;
}
</style>
